# 文件名: ex_playwright
# 当前用户: shiping.zheng
# 当前日期: 2024/10/17
# 当前时间: 17:10
# 项目名称: Flag
"""
模块描述:
    playwright登录巡天创建工单
"""
import re
import time

from PIL import Image
import pytesseract
from playwright.sync_api import Playwright, sync_playwright, expect


def run(playwright: Playwright) -> None:
    browser = playwright.chromium.launch(headless=False)
    context = browser.new_context()
    page = context.new_page()
    page.goto("https://xuntian-test2.tclpv.com/")
    page.goto("https://xuntian-test2.tclpv.com/getechLogin")
    page.get_by_placeholder("请输入用户名").click()
    page.get_by_placeholder("请输入用户名").fill("admin")
    page.get_by_placeholder("请输入用户名").press("Tab")
    page.get_by_placeholder("请输入密码").fill("tcl666")
    page.get_by_placeholder("请输入密码").press("Tab")
    # 使用角色选择器定位验证码图片
    captcha_element = page.get_by_role("img").first # 根据实际情况调整

    # 点击验证码图片
    # captcha_element.click()
    # 获取图片位置
    bounding_box = captcha_element.bounding_box()
    print("Captcha position:", bounding_box)
    # 保存验证码图片
    captcha_element.screenshot(path=r'C:\Users\shiping.zheng\Desktop\image\captcha.png')
    # 使用 Tesseract 识别验证码
    captcha_image = Image.open(r'C:\Users\shiping.zheng\Desktop\image\captcha.png')
    captcha_text = pytesseract.image_to_string(captcha_image)
    print("Captcha text:", captcha_text)
    page.get_by_placeholder("请输入左图结果").fill(captcha_text)
    page.get_by_role("button", name="登录").click()
    page.locator("i").nth(1).click()
    page.locator("li").filter(has_text="运维中心").click()
    page.get_by_text("运检服务").click()
    page.get_by_role("link", name="运检任务").click()
    page.get_by_role("button", name="新建").click()
    page.locator("div").filter(has_text=re.compile(r"^租金异常单$")).click()
    page.locator("div:nth-child(2) > .btnBox > div > .ivu-dropdown > .ivu-dropdown-rel > div > img").first.click()
    # page.locator("ul").filter(has_text=re.compile(r"^批量导入$")).get_by_role("listitem").first.click()
    page.get_by_text("批量导入").nth(2).click()
    # time.sleep(4)
    file_path = r"C:\Users\shiping.zheng\Desktop\导入模板\导入新建租金异常工单模板.xlsx"
    page.locator('input[accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"]').nth(2).set_input_files(file_path)
    # page.get_by_role("button", name="选择文件").set_input_files(file_path)
    # time.sleep(4)
    page.get_by_role("button", name="提 交").click()
    # 保持浏览器打开
    input("Press Enter to close the browser...")
    # ---------------------
    # context.close()
    # browser.close()

with sync_playwright() as playwright:
    run(playwright)
